package models

import (
	"admin-pro/appconfig"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var (
	err error
	DB  *gorm.DB
)

func Init() {
	Conf := appconfig.Config.Mysql
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		Conf.User,
		Conf.Password,
		Conf.Host,
		Conf.Port,
		Conf.Database)
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	fmt.Println("数据库连接成功")
	err = DB.AutoMigrate(
		&User{},       //用户表
		&Role{},       //角色表
		&UserRole{},   //用户角色关系表
		&Node{},       //权限表
		&NodeRole{},   //角色权限关系表
		&House{},      //仓库表
		&HouseOrder{}, //仓库订单表
	)
	if err != nil {
		panic(err)
	}
	fmt.Println("数据表迁移成功")
}
